home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 22 / Cream of the Crop 22.iso / program / cgazv4n2.zip / CPP.ZIP / LLIST.CXX < prev    next >
C/C++ Source or Header  |  1989-07-09  |  2KB  |  82 lines

  1. // LLIST.CXX : Generic Linked-List Container class
  2.  
  3. #include "llist.hxx"
  4.  
  5. llist::llist() {
  6.   // make an empty tail element:
  7.   previous = cursor = head = tail = new llist_el;
  8. }
  9.  
  10. void llist::append(void * el) {
  11.   tail->next = new llist_el;  // make a new empty tail element
  12.   tail->data = el;  // put data in the current element
  13.   tail = tail->next; // move the tail forward to the empty element
  14. }
  15.  
  16. void llist::insert(void * el) {
  17.   llist_el * new_element = new llist_el;  // make a new one
  18.   new_element->data = el;  // store the data in the new element
  19.   if ( head == cursor)  // at beginning of list
  20.     head = previous = new_element;
  21.   else {
  22.     previous->next = new_element;
  23.     previous = new_element;  // bump forward one
  24.   }
  25.   new_element->next = cursor;
  26. }
  27.  
  28. void llist::push_to_end() {
  29.   tail->next = new llist_el;  // make a new empty tail element
  30.   tail->data = cursor->data;  // current cursor data to old tail
  31.   tail = tail->next; // move tail pointer forward to new tail
  32.   previous->next = cursor->next; // unlink current element
  33.   delete cursor;  // free the storage (no destructor called)
  34.   cursor = previous->next; // reposition the cursor
  35. }
  36.  
  37. int llist::remove() {
  38.   // If you are at the tail (includes empty list):
  39.   if ( cursor == tail ) return 1;  // can't delete tail
  40.   delete_data(cursor->data);  // virtual function deletes properly
  41.   if ( cursor == head ) {
  42.     head = previous = cursor->next;  // move to the next element
  43.     delete cursor;
  44.     cursor = head;
  45.     return 0;
  46.   }
  47.   previous->next = cursor->next;  // bypass the current element
  48.   delete cursor;
  49.   cursor = previous->next;
  50.   return 0;
  51. }
  52.  
  53. void llist::reset() {
  54.   previous = cursor = head;
  55. }
  56.  
  57. int llist::next() {
  58.   if ( cursor == tail ) return 0;  // end of list
  59.   // if you just reset the cursor, don't move "previous"
  60.   if ( previous != cursor )
  61.     previous = previous->next;  
  62.   cursor = cursor->next;
  63.   return 1;
  64. }
  65.  
  66. int llist::end() {
  67.   if (cursor == tail) return 1;
  68.   else return 0;
  69. }
  70.  
  71. void * llist::value() {
  72.   if ( cursor == tail ) return 0; // (if head == tail, this is true, too)
  73.   return cursor->data;
  74. }
  75.  
  76. llist::~llist() {
  77.   reset();
  78.   while(!end())
  79.     remove();
  80.   delete tail;  // no data in tail
  81. }
  82.